﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Client
{
    public partial class FormClient : Form
    {
        public FormClient()
        {
            InitializeComponent();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            SendMessage();
        }

        public void SendMessage()
        {
            #region tpcclient
            /*
            try
            {
                TcpClient client = new TcpClient("127.0.0.1", 5567);
                NetworkStream sendStream = client.GetStream();
                //StreamWriter writer = new StreamWriter(sendStream);
                String msg = this.richTextBoxSend.Text;
                Byte[] sendBytes = Encoding.Default.GetBytes(msg);
                sendStream.Write(sendBytes, 0, sendBytes.Length);
                //writer.Flush();
                sendStream.Close();
                client.Close();

            }
            catch (System.Exception)
            {
            }
            */
            #endregion

            #region socket communication
            try
            {
                int port = 2000;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

                c.Connect(ipe);//连接到服务器
                string sendStr = this.richTextBoxSend.Text;

                //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                byte[] bs = Encoding.Unicode.GetBytes(sendStr);

                c.Send(bs, bs.Length, 0);//发送测试信息
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                this.richTextBoxReceive.Text = recvStr;

                c.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            #endregion
        }
    }
}
